<template>
  <div class="judge-info-display">
    <!-- 简洁模式 -->
    <div v-if="mode === 'simple'" class="simple-mode">
      <a-tag
        :color="getStatusColor(judgeInfo?.message)"
        class="status-tag"
        @click="showDetail = true"
      >
        <component :is="getStatusIcon(judgeInfo?.message)" />
        {{ getStatusText(judgeInfo?.message) }}
      </a-tag>

      <div class="metrics-simple" v-if="hasMetrics">
        <span class="metric-item" v-if="judgeInfo?.time !== null">
          <ClockCircleOutlined />
          {{ formatTime(judgeInfo.time) }}
        </span>
        <span class="metric-item" v-if="judgeInfo?.memory !== null">
          <DatabaseOutlined />
          {{ formatMemory(judgeInfo.memory) }}
        </span>
      </div>
    </div>

    <!-- 详细模式 -->
    <div v-else-if="mode === 'detailed'" class="detailed-mode">
      <div class="status-header">
        <a-tag
          :color="getStatusColor(judgeInfo?.message)"
          class="status-tag-large"
        >
          <component :is="getStatusIcon(judgeInfo?.message)" />
          {{ getStatusText(judgeInfo?.message) }}
        </a-tag>
      </div>

      <div class="metrics-detailed" v-if="hasMetrics">
        <div class="metric-card">
          <div class="metric-label">
            <ClockCircleOutlined />
            执行时间
          </div>
          <div class="metric-value">
            {{ formatTime(judgeInfo?.time) }}
          </div>
          <div class="metric-bar" v-if="judgeInfo?.time && timeLimit">
            <a-progress
              :percent="getTimePercent()"
              :stroke-color="getTimeColor()"
              :show-info="false"
              size="small"
            />
          </div>
        </div>

        <div class="metric-card">
          <div class="metric-label">
            <DatabaseOutlined />
            内存使用
          </div>
          <div class="metric-value">
            {{ formatMemory(judgeInfo?.memory) }}
          </div>
          <div class="metric-bar" v-if="judgeInfo?.memory && memoryLimit">
            <a-progress
              :percent="getMemoryPercent()"
              :stroke-color="getMemoryColor()"
              :show-info="false"
              size="small"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 卡片模式 -->
    <div v-else-if="mode === 'card'" class="card-mode">
      <a-card size="small" class="judge-card">
        <div class="card-header">
          <a-tag
            :color="getStatusColor(judgeInfo?.message)"
            class="status-tag-card"
          >
            <component :is="getStatusIcon(judgeInfo?.message)" />
            {{ getStatusText(judgeInfo?.message) }}
          </a-tag>
        </div>

        <div class="card-content" v-if="hasMetrics">
          <a-row :gutter="16">
            <a-col :span="12" v-if="judgeInfo?.time !== null">
              <a-statistic
                title="执行时间"
                :value="judgeInfo.time"
                suffix="ms"
                :value-style="{ fontSize: '14px', color: getTimeColor() }"
              >
                <template #prefix>
                  <ClockCircleOutlined />
                </template>
              </a-statistic>
            </a-col>
            <a-col :span="12" v-if="judgeInfo?.memory !== null">
              <a-statistic
                title="内存使用"
                :value="formatMemoryValue(judgeInfo.memory)"
                :suffix="getMemoryUnit(judgeInfo.memory)"
                :value-style="{ fontSize: '14px', color: getMemoryColor() }"
              >
                <template #prefix>
                  <DatabaseOutlined />
                </template>
              </a-statistic>
            </a-col>
          </a-row>
        </div>
      </a-card>
    </div>

    <!-- 详情弹窗 -->
    <a-modal
      v-model:open="showDetail"
      title="判题详情"
      :footer="null"
      width="500"
      class="judge-detail-modal"
    >
      <div class="detail-content">
        <div class="detail-status">
          <div class="status-icon">
            <component :is="getStatusIcon(judgeInfo?.message)" />
          </div>
          <div class="status-info">
            <h3 class="status-title">{{ getStatusText(judgeInfo?.message) }}</h3>
            <p class="status-desc">{{ getStatusDescription(judgeInfo?.message) }}</p>
          </div>
        </div>

        <a-divider />

        <div class="detail-metrics" v-if="hasMetrics">
          <h4>执行指标</h4>
          <div class="metrics-grid">
            <div class="metric-item-detail" v-if="judgeInfo?.time !== null">
              <div class="metric-icon">
                <ClockCircleOutlined />
              </div>
              <div class="metric-info">
                <div class="metric-name">执行时间</div>
                <div class="metric-val">{{ formatTime(judgeInfo.time) }}</div>
                <div class="metric-progress" v-if="timeLimit">
                  <a-progress
                    :percent="getTimePercent()"
                    :stroke-color="getTimeColor()"
                    size="small"
                  />
                </div>
              </div>
            </div>

            <div class="metric-item-detail" v-if="judgeInfo?.memory !== null">
              <div class="metric-icon">
                <DatabaseOutlined />
              </div>
              <div class="metric-info">
                <div class="metric-name">内存使用</div>
                <div class="metric-val">{{ formatMemory(judgeInfo.memory) }}</div>
                <div class="metric-progress" v-if="memoryLimit">
                  <a-progress
                    :percent="getMemoryPercent()"
                    :stroke-color="getMemoryColor()"
                    size="small"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>

        <a-divider />

        <div class="raw-data">
          <h4>原始数据</h4>
          <pre class="json-display">{{ JSON.stringify(judgeInfo, null, 2) }}</pre>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  ExclamationCircleOutlined,
  ClockCircleOutlined,
  DatabaseOutlined,
  QuestionCircleOutlined,
  SyncOutlined
} from '@ant-design/icons-vue'

interface JudgeInfo {
  message: string
  memory: string | null
  time: string | null
}

interface Props {
  judgeInfo: JudgeInfo | null
  mode?: 'simple' | 'detailed' | 'card'
  timeLimit?: number // 时间限制 (ms)
  memoryLimit?: number // 内存限制 (KB)
}

const props = withDefaults(defineProps<Props>(), {
  mode: 'simple',
  timeLimit: 1000,
  memoryLimit: 128 * 1024 // 128MB
})

const showDetail = ref(false)

// 计算属性
const hasMetrics = computed(() => {
  return props.judgeInfo && (
    props.judgeInfo.time !== null ||
    props.judgeInfo.memory !== null
  )
})

// 获取状态文本
const getStatusText = (message: string) => {
  const statusMap: Record<string, string> = {
    'Accepted': '通过',
    'Wrong Answer': '答案错误',
    'Time Limit Exceeded': '超时',
    'Memory Limit Exceeded': '内存超限',
    'Runtime Error': '运行错误',
    'Compile Error': '编译错误',
    'Presentation Error': '格式错误',
    'System Error': '系统错误',
    'Pending': '等待中',
    'Judging': '判题中'
  }
  return statusMap[message] || message || '未知状态'
}

// 获取状态颜色
const getStatusColor = (message: string) => {
  const colorMap: Record<string, string> = {
    'Accepted': 'success',
    'Wrong Answer': 'error',
    'Time Limit Exceeded': 'warning',
    'Memory Limit Exceeded': 'warning',
    'Runtime Error': 'error',
    'Compile Error': 'error',
    'Presentation Error': 'warning',
    'System Error': 'error',
    'Pending': 'default',
    'Judging': 'processing'
  }
  return colorMap[message] || 'default'
}

// 获取状态图标
const getStatusIcon = (message: string) => {
  const iconMap: Record<string, any> = {
    'Accepted': CheckCircleOutlined,
    'Wrong Answer': CloseCircleOutlined,
    'Time Limit Exceeded': ClockCircleOutlined,
    'Memory Limit Exceeded': DatabaseOutlined,
    'Runtime Error': ExclamationCircleOutlined,
    'Compile Error': ExclamationCircleOutlined,
    'Presentation Error': ExclamationCircleOutlined,
    'System Error': ExclamationCircleOutlined,
    'Pending': ClockCircleOutlined,
    'Judging': SyncOutlined
  }
  return iconMap[message] || QuestionCircleOutlined
}

// 获取状态描述
const getStatusDescription = (message: string) => {
  const descMap: Record<string, string> = {
    'Accepted': '恭喜！您的代码通过了所有测试用例',
    'Wrong Answer': '您的代码输出结果与期望结果不符',
    'Time Limit Exceeded': '您的代码执行时间超过了限制',
    'Memory Limit Exceeded': '您的代码使用的内存超过了限制',
    'Runtime Error': '您的代码在运行时发生了错误',
    'Compile Error': '您的代码编译失败',
    'Presentation Error': '您的代码输出格式不正确',
    'System Error': '系统发生错误，请稍后重试',
    'Pending': '您的提交正在等待判题',
    'Judging': '正在对您的代码进行判题'
  }
  return descMap[message] || '未知状态'
}

// 格式化时间
const formatTime = (time: string | null) => {
  if (time === null || time === undefined) return '--'
  const timeNum = parseInt(time)
  if (timeNum === 0) return '< 1ms'
  if (timeNum < 1000) return `${timeNum}ms`
  return `${(timeNum / 1000).toFixed(2)}s`
}

// 格式化内存
const formatMemory = (memory: string | null) => {
  if (memory === null || memory === undefined) return '--'
  const memoryNum = parseInt(memory)
  if (memoryNum === 0) return '< 1KB'
  if (memoryNum < 1024) return `${memoryNum}KB`
  if (memoryNum < 1024 * 1024) return `${(memoryNum / 1024).toFixed(1)}MB`
  return `${(memoryNum / 1024 / 1024).toFixed(1)}GB`
}

// 格式化内存数值（用于统计组件）
const formatMemoryValue = (memory: string | null) => {
  if (memory === null || memory === undefined) return 0
  const memoryNum = parseInt(memory)
  if (memoryNum < 1024) return memoryNum
  if (memoryNum < 1024 * 1024) return (memoryNum / 1024).toFixed(1)
  return (memoryNum / 1024 / 1024).toFixed(1)
}

// 获取内存单位
const getMemoryUnit = (memory: string | null) => {
  if (memory === null || memory === undefined) return 'KB'
  const memoryNum = parseInt(memory)
  if (memoryNum < 1024) return 'KB'
  if (memoryNum < 1024 * 1024) return 'MB'
  return 'GB'
}

// 获取时间百分比
const getTimePercent = () => {
  if (!props.judgeInfo?.time || !props.timeLimit) return 0
  const timeNum = parseInt(props.judgeInfo.time)
  return Math.min((timeNum / props.timeLimit) * 100, 100)
}

// 获取内存百分比
const getMemoryPercent = () => {
  if (!props.judgeInfo?.memory || !props.memoryLimit) return 0
  const memoryNum = parseInt(props.judgeInfo.memory)
  return Math.min((memoryNum / props.memoryLimit) * 100, 100)
}

// 获取时间颜色
const getTimeColor = () => {
  const percent = getTimePercent()
  if (percent < 50) return '#52c41a'
  if (percent < 80) return '#faad14'
  return '#ff4d4f'
}

// 获取内存颜色
const getMemoryColor = () => {
  const percent = getMemoryPercent()
  if (percent < 50) return '#52c41a'
  if (percent < 80) return '#faad14'
  return '#ff4d4f'
}
</script>

<style scoped>
.judge-info-display {
  display: inline-block;
}

/* 简洁模式 */
.simple-mode {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.status-tag {
  display: flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
}

.status-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.metrics-simple {
  display: flex;
  gap: 8px;
}

.metric-item {
  display: flex;
  align-items: center;
  gap: 2px;
  font-size: 12px;
  color: #8c8c8c;
  background: #f5f5f5;
  padding: 2px 6px;
  border-radius: 4px;
}

/* 详细模式 */
.detailed-mode {
  width: 100%;
}

.status-header {
  margin-bottom: 12px;
}

.status-tag-large {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 600;
  padding: 6px 12px;
}

.metrics-detailed {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.metric-card {
  flex: 1;
  min-width: 120px;
  background: #fafafa;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  padding: 12px;
}

.metric-label {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #8c8c8c;
  margin-bottom: 4px;
}

.metric-value {
  font-size: 16px;
  font-weight: 600;
  color: #262626;
  margin-bottom: 8px;
}

.metric-bar {
  margin-top: 8px;
}

/* 卡片模式 */
.card-mode {
  width: 100%;
}

.judge-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.card-header {
  margin-bottom: 12px;
}

.status-tag-card {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 600;
}

.card-content {
  margin-top: 16px;
}

/* 详情弹窗 */
.judge-detail-modal :deep(.ant-modal-header) {
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

.detail-content {
  padding: 16px 0;
}

.detail-status {
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.status-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: #f0f7ff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #1890ff;
}

.status-info {
  flex: 1;
}

.status-title {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: #262626;
}

.status-desc {
  margin: 0;
  color: #8c8c8c;
  line-height: 1.5;
}

.detail-metrics h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #262626;
}

.metrics-grid {
  display: grid;
  gap: 16px;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}

.metric-item-detail {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px;
  background: #fafafa;
  border-radius: 8px;
  border: 1px solid #f0f0f0;
}

.metric-icon {
  width: 32px;
  height: 32px;
  border-radius: 6px;
  background: #e6f7ff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  color: #1890ff;
}

.metric-info {
  flex: 1;
}

.metric-name {
  font-size: 12px;
  color: #8c8c8c;
  margin-bottom: 4px;
}

.metric-val {
  font-size: 16px;
  font-weight: 600;
  color: #262626;
  margin-bottom: 8px;
}

.metric-progress {
  margin-top: 8px;
}

.raw-data h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #262626;
}

.json-display {
  background: #f6f8fa;
  border: 1px solid #e1e4e8;
  border-radius: 6px;
  padding: 12px;
  font-size: 12px;
  line-height: 1.4;
  margin: 0;
  overflow-x: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .metrics-detailed {
    flex-direction: column;
  }

  .metrics-grid {
    grid-template-columns: 1fr;
  }

  .detail-status {
    flex-direction: column;
    text-align: center;
  }
}
</style>
